<template>
  <header>
    <div class="page-box">
      <router-link class="logo" key="home" :to="{ name: 'home' }">WEB3</router-link>
      <!-- <div class="logo">WEB3</div> -->
      <div class="menu" v-if="route.name != 'home'">
        <router-link class="menu-item" key="home" :to="{ name: 'home' }">Home</router-link>
        <router-link
          class="menu-item"
          :class="route.name === item.name ? 'active' : ''"
          v-for="item in menuList"
          :to="{ name: item.name }"
          :key="item.name"
          >{{ item.title }}</router-link
        >
      </div>
      <div class="account">
        <!-- network, account, balance -->
        <el-button
          v-if="account === ''"
          :loading="connectLoading"
          type="primary"
          @click="connectMetaMask"
          >Connect Wallet</el-button
        >
        <template v-else>
          <el-tag style="margin-right: 8px">{{ fmtAccount }}</el-tag>
          <el-tag style="margin-right: 8px">{{ balanceFixed }} ETH</el-tag>
          <el-tag style="margin-right: 8px" v-if="network.name">{{ network.name }}</el-tag>
          <el-button type="danger" size="small" @click="disconnect">Disconnect</el-button>
        </template>
      </div>
    </div>

    <a
      :href="`https://goerli.etherscan.io/block/${blockNumber}`"
      target="_blank"
      class="block-number"
      ><span></span>{{ blockNumber }}</a
    >
  </header>
</template>

<script lang="ts" setup>
import { useRoute } from 'vue-router'
import { computed, onMounted, ref, watchEffect } from 'vue'
import { truncateAddress, _isMobile } from '@/utils/index'
import menu from '@/hooks/menu'
import { useAccountStore } from '@/stores/account'
import { useConnectorStore } from '@/stores/connector'
import { storeToRefs } from 'pinia'
import { ProviderTypes } from '@/ethers-core'
import { ElMessage, ElNotification } from 'element-plus'

const { menuList } = menu()

const connectorStore = useConnectorStore()
const { account } = storeToRefs(connectorStore)
const { disconnect } = connectorStore

const accountStore = useAccountStore()
const { balanceFixed, blockNumber, network } = storeToRefs(accountStore)

onMounted(() => {
  if (localStorage.getItem('ProviderTypes') === ProviderTypes.Metamask) {
    connectorStore.initProvider(ProviderTypes.Metamask)
  }
  if (localStorage.getItem('ProviderTypes') === ProviderTypes.WalletConnect) {
    connectorStore.initProvider(ProviderTypes.WalletConnect)
  }
})

watchEffect(() => {
  if (network.value.chainId != 0 && network.value.chainId != 5) {
    ElNotification({
      title: 'Network Error',
      dangerouslyUseHTMLString: true,
      showClose: false,
      message:
        '<div>请点击切换 <span style="color:var(--el-color-primary);cursor: pointer;">Ethereum Goerli</span> 测试网络。</div>',
      duration: 0,
      onClick: () => {
        // todo: 判断是否支持切换
        window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [
            {
              chainId: '0x5',
            },
          ],
        })
      },
    })
  } else {
    ElNotification.closeAll()
  }
})

const connectLoading = ref(false)
async function connectMetaMask() {
  connectLoading.value = true
  try {
    if (_isMobile()) {
      await connectorStore.initProvider(ProviderTypes.WalletConnect)
    } else {
      await connectorStore.initProvider(ProviderTypes.Metamask)
    }
  } catch (error) {
    console.log('[ error ] >', error)
  }
  connectLoading.value = false
}

const route = useRoute()
const fmtAccount = computed(() => {
  return truncateAddress(account.value)
})
</script>

<style scoped lang="less">
header {
  padding: 20px;
  background-color: #fff;
  .page-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .logo {
    margin-right: 20px;
    font-size: 22px;
    font-weight: bold;
    line-height: 40px;
    color: #333;
  }
  .menu {
    flex: 1;
    display: flex;
    .menu-item {
      line-height: 38px;
      margin: 0 8px;
      padding: 0 8px;
      border-bottom: 2px solid transparent;
      transition: 0.2s ease;
      color: #333;
      &.active {
        color: var(--el-color-primary);
        border-bottom-color: var(--el-color-primary);
      }
      &:hover {
        color: var(--el-color-primary);
        border-bottom-color: var(--el-color-primary);
      }
    }
  }
  .account {
    margin-left: 20px;
    display: flex;
    align-items: center;
  }
}
.block-number {
  position: fixed;
  z-index: 999999;
  bottom: 80px;
  right: 80px;
  color: green;
  font-size: 14px;
  line-height: 20px;
  span {
    display: inline-block;
    vertical-align: middle;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    overflow: hidden;
    background-color: rgba(0, 128, 0, 1);
    margin-right: 8px;
  }
}

@media screen and (max-width: 992px) {
  header {
    .account {
      .el-tag {
        display: none;
        &:first-child {
          display: inline-flex;
        }
      }
    }
    .menu {
      display: none;
    }
  }
  .block-number {
    bottom: 20px;
    right: 20px;
  }
}
</style>
